package myservice.android.activities;

import java.util.ArrayList;

import myservice.android.Global;
import myservice.android.R;
import myservice.android.database.Database;
import myservice.android.utilities.PopupMenu;
import myservice.android.utilities.Record;
import myservice.android.utilities.RecordAdapter;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class PublicationListActivity extends BaseActivity {
	
	private TextView allPublicationsText, interestedNameText;
	private Button addPublicationButton;
	private ArrayList<Record> allPublicationData;
	private ListView allPublicationList;
	private TextView noPublicationsDefinedText;
	private ArrayList<Record> ownedPublicationData;
	private ListView ownedPublicationList;
	private View horizontalDivider;
	private TextView noPublicationsOwnedText;	
	private RecordAdapter allPublicationAdapter, ownedPublicationAdapter;
	private RelativeLayout ownedPublicationsLayout;
	private long personId; // 0=display all publications only
	private long assignedPubId = 0;
	
	@Override
	protected void initializeLayoutIdAndTitle() {
		
		layoutId = R.layout.publication_list;
		activityTitle = Global.res.getString(R.string.title_publications);
		
	}

	@Override
	protected void retrieveViews() {

    	allPublicationsText = (TextView) findViewById(R.id.allPublicationsText);
    	interestedNameText = (TextView) findViewById(R.id.interestedName);
        addPublicationButton = (Button) findViewById(R.id.newPublicationButton);
        allPublicationList = (ListView) findViewById(R.id.publicationsList);
        noPublicationsDefinedText = (TextView) findViewById(R.id.noPublicationsMessage);
        ownedPublicationList = (ListView) findViewById(R.id.ownedPublicationsList);
        noPublicationsOwnedText = (TextView) findViewById(R.id.noOwnedPublicationsMessage); 
        ownedPublicationsLayout = (RelativeLayout) findViewById(R.id.ownedPublications);
        horizontalDivider = (View) findViewById(R.id.leftDivider); 
		
	}

	@Override
	protected void loadActivityParameters() {
		
		personId = activityParameters.getLong("person_id");
		
	}

	@Override
	protected void assignListeners() {

        addPublicationButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				final Dialog dialog = new Dialog(PublicationListActivity.this);
				dialog.setContentView(R.layout.add_publication_dialog);
				dialog.setTitle(Global.res.getString(R.string.title_add_new_publication));
				
				Button saveButton = (Button) dialog.findViewById(R.id.saveButton);				
				Button cancelButton = (Button) dialog.findViewById(R.id.cancelButton);
				final Spinner type = (Spinner) dialog.findViewById(R.id.publicationTypeSpinner);
				final EditText titleField = (EditText) dialog.findViewById(R.id.titleField);
				
				saveButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {					
						Database.execSQL("INSERT INTO publications (publicationid,title,type,timestamp) VALUES ("+Database.getUniqueRowId("publications")+
								         ",'"+Global.fixText(titleField.getText())+"',"+type.getSelectedItemPosition()+","+Global.getTimeStamp()+")");	
						dialog.dismiss();
						updateLeftList();
					}			
				});
				
				cancelButton.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						dialog.dismiss();				
					}			
				});		
				
				dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);				
				
				dialog.show();								
			}
        });  
		
	}		          
    
	private void updateLeftList() {
		
    	PopupMenu.createPopupMenu(this);
		PopupMenu.menuSection4.setVisibility(View.GONE);
		
		allPublicationData = new ArrayList<Record>();		
    	Cursor cursor = Database.select("SELECT * FROM publications WHERE timestamp<>"+Global.TIMESTAMP_DELETED+" ORDER BY type,title");    	
    	boolean noPublicationsDefined = true;

    	while (cursor.moveToNext()) {
    		noPublicationsDefined=false;
    		Record publication = new Record();
    		publication.id=cursor.getInt(cursor.getColumnIndex("publicationid"));
    		publication.secondLine=cursor.getString(cursor.getColumnIndex("title"));
    		publication.status=cursor.getInt(cursor.getColumnIndex("type"));    		
    		allPublicationData.add(publication);
    	}	
    	cursor.close();    	 
    	
    	if (noPublicationsDefined==true)
    		noPublicationsDefinedText.setVisibility(View.VISIBLE);
    	else {
    		noPublicationsDefinedText.setVisibility(View.GONE);
    	}
    	
        allPublicationAdapter = new RecordAdapter(this, R.layout.list_row, allPublicationData, 2);
        allPublicationList.setAdapter(allPublicationAdapter);
        
        allPublicationList.setOnItemLongClickListener(new OnItemLongClickListener () {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				final long pid = allPublicationData.get(position).id;					
				
				PopupMenu.menuHeading.setText(allPublicationData.get(position).secondLine);
				
				PopupMenu.menuOption1.setText(Global.res.getString(R.string.menuitem_modify_publication));	
				PopupMenu.menuOption2.setText(Global.res.getString(R.string.menuitem_assign_to));
				PopupMenu.menuOption3.setText(Global.res.getString(R.string.menuitem_delete_publication));						
				
				PopupMenu.menuOption1.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						PopupMenu.closeMenu();
						editPublication(pid);				
					}					
				});
				
				PopupMenu.menuOption2.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						PopupMenu.closeMenu();
						assignedPubId = pid;
						Intent i = new Intent(getApplicationContext(),PersonListActivity.class);
						i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
						i.putExtra("mode",1);
						startActivity(i);			
					}					
				});				
				
				PopupMenu.menuOption3.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						PopupMenu.closeMenu();
						AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(PublicationListActivity.this);
						alertDialogBuilder.setTitle(Global.res.getText(R.string.title_warning));				
						alertDialogBuilder
							.setMessage(Global.res.getText(R.string.message_delete_publication_confirmation))
							.setPositiveButton(Global.res.getText(R.string.button_yes),new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,int id) {
									Database.deletePublication(pid);
									updateLeftList();
									updateRightList();
								}
							  })
							.setNegativeButton(Global.res.getText(R.string.button_no),new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.cancel();
								}
							});
				 
						AlertDialog alertDialog = alertDialogBuilder.create();
						alertDialog.show();				
					}					
				});										
				
				PopupMenu.showMenu(view);				
				
				return true;
			}
        	
        });        
        
        allPublicationList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
						 
					clickPublication(allPublicationData.get(position).id);
			}
        	
        });
    	
	} 
	
	private void editPublication(long publicationId) {		
		Intent i = new Intent(getApplicationContext(),PublicationActivity.class);
		i.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		i.putExtra("publication_id",publicationId);
		startActivity(i);			
	}
	
	private void clickPublication(long publicationId) {

		if (personId==0) {			
			editPublication(publicationId);
		} else {			
			assignPublicationToPerson(publicationId,personId);	
			updateRightList();
		}		
		
	}

	private void updateRightList() {
		if (personId==0)
			return;
		
		ownedPublicationData = new ArrayList<Record>();		
    	Cursor cursor = Database.select("SELECT placedpublications.publicationid AS p, title, type FROM placedpublications JOIN publications ON placedpublications.publicationid=publications.publicationid "+
    										   "WHERE personid="+personId+" AND placedpublications.timestamp<>"+Global.TIMESTAMP_DELETED+" AND placed=1 ORDER BY type,title");    	    	     
    	
    	boolean noPublicationsGiven = true;

    	while (cursor.moveToNext()) {
    		noPublicationsGiven=false;
    		Record publication = new Record();
    		publication.id=cursor.getInt(cursor.getColumnIndex("p"));
    		publication.secondLine=cursor.getString(cursor.getColumnIndex("title"));
    		publication.status=cursor.getInt(cursor.getColumnIndex("type"));    		
    		ownedPublicationData.add(publication);
    	}	
    	cursor.close();    	 
    	
    	if (noPublicationsGiven==true)
    		noPublicationsOwnedText.setVisibility(View.VISIBLE);
    	else
    		noPublicationsOwnedText.setVisibility(View.GONE);
    	
        ownedPublicationAdapter = new RecordAdapter(this, R.layout.list_row, ownedPublicationData, 2);
        ownedPublicationList.setAdapter(ownedPublicationAdapter);
        
        ownedPublicationList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position,
					long id) {
				Database.execSQL("UPDATE placedpublications SET placed=0, timestamp="+Global.getTimeStamp()+" WHERE publicationid="+ownedPublicationData.get(position).id+" AND personid="+personId);
				updateRightList();						 					
			}
        	
        });
    	
	}    
	
	private void assignPublicationToPerson(long pubId, long personId) {
		Cursor cursor = Database.select("SELECT publicationid FROM placedpublications WHERE publicationid="+pubId+" AND personid="+personId);			
		if (cursor.moveToNext()==false)						
			Database.execSQL("INSERT INTO placedpublications (publicationid, personid, placed, timestamp) VALUES ("+pubId+","+personId+",1,"+Global.getTimeStamp()+")");
		else
			Database.execSQL("UPDATE placedpublications SET placed=1, timestamp="+Global.getTimeStamp()+" WHERE publicationid="+pubId+" AND personid="+personId);
		cursor.close();	
		if (this.personId==0)
			Global.displayToast(this, Global.res.getString(R.string.message_publication_assigned));
	}

	@Override
	protected void updateUi() {
		
    	if (Global.selectedId!=0) {
    		assignPublicationToPerson(assignedPubId,Global.selectedId);
    		Global.selectedId=0;
    	}

        if (personId==0) {
        	allPublicationsText.setVisibility(View.GONE);
        	ownedPublicationsLayout.setVisibility(View.GONE);
        	horizontalDivider.setVisibility(View.GONE);
        } else {
        	Cursor cursor = Database.select("SELECT name FROM persons WHERE personid="+personId);
        	if (cursor.moveToNext()==true)
        		interestedNameText.setText(cursor.getString(cursor.getColumnIndex("name")));
        	cursor.close();
        }
        
    	updateLeftList();
    	updateRightList();
		
	}	
	
}
